import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Button, DatePicker, Empty, Form, Icon, Input, message } from 'antd';
import { useRequest } from '@/hooks';
import useDynamicList from '@/hooks/useDynamicList';
import moment from 'moment';
import { formatDateRange } from '@/utils/utils';
import FormContainer from './FormContainer';

const RANGE_PICKER_FORMAT_YYYY_MM_DD = 'YYYY-MM-DD';

/**
 * 员工档案 - 培训经历
 */
const TrainingExperienceSection = ({ formData, onChange, readonly, saveAction, ...props }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 列表管理
    const {
        list: trainList,
        remove: trainListRemove,
        push: trainListPush,
        getKey: trainListGetKey,
        resetList: trainListReset
    } = useDynamicList([]);

    useEffect(() => {
        // 重置列表的值
        trainListReset(formData.trainList);
    }, [trainListReset, formData.trainList]);

    useEffect(() => {
        // 表单赋值
        formRef.current.getFieldDecorator('trainList', { initialValue: formData.trainList || [] });
    }, [formData.trainList]);

    // 保存
    const handleSubmit = async values => {
        const submitData = Object.assign({
            entryPersonnelCode: formData.entryPersonnelCode,
            newList: trainList.map((item, index) => {
                const key = trainListGetKey(index);
                return {
                    startTime: values.startTime[key][0]?.format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    endTime: values.startTime[key][1]?.format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    // trainTime: values.trainTime[key] ? values.trainTime[key] : null, // 培训时长
                    trainContent: values.trainContent[key] ? values.trainContent[key] : null,
                    trainOrganize: values.trainOrganize[key] ? values.trainOrganize[key] : null,
                    certificate: values.certificate[key] ? values.certificate[key] : null
                };
            })
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData.newList);
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        trainListReset(formData.trainList);
    };

    // 取消编辑
    const handleEdit = () => {
        if (trainList.length === 0) {
            trainListPush({});
        }
    };

    // 处理日期为空的情况
    const handleDealDateEmpty = (startDate, endDate) => {
        if (startDate === '' || endDate === '' || !startDate || !endDate) {
            return undefined;
        }
        return [moment(startDate), moment(endDate)];
    };

    // 很奇怪, 日期选择组件不能自动赋值
    const handleSetStartTimeValue = (values, keys) => {
        formRef.current.setFieldsValue({ [keys]: values });
    };

    // render
    return (
        <FormContainer
            ref={formRef}
            title="培训经历"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onEdit={handleEdit}
            {...props}
        >
            {({ getFieldDecorator }, editStatus) => (
                <div className="dynamicList">
                    {trainList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    <div className="dynamicListContainer">
                        {trainList.map((item, index) => (
                            <div key={trainListGetKey(index)} className="dynamicListItem">
                                {editStatus && props.isEntryGuide && (
                                    <div className="dynamicListItemHeader">培训经历 {index + 1}</div>
                                )}
                                {editStatus && (
                                    <Icon
                                        onClick={() => trainListRemove(index)}
                                        className="dynamicListClose"
                                        type="close-circle"
                                        theme="filled"
                                    />
                                )}
                                <Form.Item label="起止时间">
                                    {editStatus
                                        ? getFieldDecorator(`startTime[${trainListGetKey(index)}]`, {
                                              initialValue: handleDealDateEmpty(item?.startTime, item?.endTime)
                                          })(
                                              <DatePicker.RangePicker
                                                  style={{ width: '100%' }}
                                                  format={RANGE_PICKER_FORMAT_YYYY_MM_DD}
                                                  onPanelChange={values =>
                                                      handleSetStartTimeValue(
                                                          values,
                                                          `startTime[${trainListGetKey(index)}]`
                                                      )
                                                  }
                                              />
                                          )
                                        : formatDateRange(item?.startTime, item?.endTime, 'YYYY-MM-DD') || '--'}
                                </Form.Item>
                                <Form.Item label="培训主题/内容">
                                    {editStatus ? (
                                        getFieldDecorator(`trainContent[${trainListGetKey(index)}]`, {
                                            initialValue: item?.trainContent ?? undefined,
                                            rules: [
                                                { required: true, message: '请填写培训主题' },
                                                { max: 100, message: '字数不能超过100个字符' }
                                            ]
                                        })(<Input maxLength={100} placeholder="请输入培训主题/内容" />)
                                    ) : (
                                        <div className="multiLineText">{item?.trainContent || '--'}</div>
                                    )}
                                </Form.Item>
                                <Form.Item label="证书">
                                    {editStatus ? (
                                        getFieldDecorator(`certificate[${trainListGetKey(index)}]`, {
                                            initialValue: item?.certificate ?? undefined
                                        })(<Input minLength={1} maxLength={50} placeholder="请输入证书" />)
                                    ) : (
                                        <span>{item?.certificate || '--'}</span>
                                    )}
                                </Form.Item>
                                <Form.Item label="培训机构">
                                    {editStatus ? (
                                        getFieldDecorator(`trainOrganize[${trainListGetKey(index)}]`, {
                                            initialValue: item?.trainOrganize ?? undefined,
                                            rules: [
                                                { required: true, message: '请填写培训机构' },
                                                { max: 100, message: '字数不能超过100个字符' }
                                            ]
                                        })(<Input maxLength={100} placeholder="请填写培训机构" />)
                                    ) : (
                                        <div className="multiLineText">{item?.trainOrganize || '--'}</div>
                                    )}
                                </Form.Item>
                            </div>
                        ))}
                    </div>
                    {editStatus ? (
                        <Button className="dynamicListAddButton" block onClick={() => trainListPush({})}>
                            +添加培训经历
                        </Button>
                    ) : null}
                </div>
            )}
        </FormContainer>
    );
};

// prop
TrainingExperienceSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

TrainingExperienceSection.defaultProps = {
    saveAction: null,
    readonly: false
};

export default TrainingExperienceSection;
